<?php

namespace App\Http\Controllers\mobile;

use Illuminate\Support\Facades\Input;
use App\Models\Book;
use App\Models\Section;

class BookController extends BaseController {
	
	public function show($id) {
		$book = Book::find($id);
		if(is_null($book)) {
			return redirect('/mobile/404');
		}
		$book->clicks = ($book->clicks + 1);
		$book->save();
		$newSections = Section::select(['id', 'name', 'order'])
				->where('book_id', $book->id)
				->orderBy('order', 'desc')
				->take(10)
				->get();
		$hotBooks = Book::where('id', '!=', $book->id)
				->where('category_id', $book->category_id)
				->orderBy('clicks', 'desc')
				->take(5)
				->get();
		return view('mobile.book', compact('book', 'newSections', 'hotBooks'));
	}
	
	public function sections($id) {
		$sort = Input::get('sort');
		if(empty($sort)) {
			$sort = 'asc';
		}
		$book = Book::find($id);
		if(is_null($book)) {
			return redirect('/mobile/404');
		}
		$book->clicks = ($book->clicks + 1);
		$book->save();
		$sections = $book->sections()->select(['id', 'name', 'order'])->orderBy('order', $sort)->paginate(100);
		$sOrder = session($book->id);
		return view('mobile.sections', compact('sections', 'book', 'sort', 'sOrder'));
	}
	
	public function download($id) {
		$book = Book::find($id);
		if(is_null($book)) {
			return redirect('/mobile/404');
		}
		$hasTxt = file_exists(base_path('public/downloads/txt/'.$book->id.'.txt'));
		if(!$hasTxt) {
			$sections = Section::select(['id', 'name', 'content'])
				->where('book_id', $book->id)
				->orderBy('order', 'asc')
				->get();
			$data = "《".$book->name."》 \n";
			$data .= "简介：\n".strip_tags(str_replace('&nbsp;', '', $book->abstract));
			foreach ($sections as $section) {
				$data .= "\n".$section->name."\n";
				$data .= strip_tags(str_replace('<br />', " \n ", str_replace('&nbsp;', '', $section->content)));
				$data .= strip_tags(str_replace('<p>', '', str_replace('</p>', " \n ", str_replace('&emsp;', '', $section->content))));
			}
			file_put_contents(base_path('public/downloads/txt/'.$book->id.'.txt'), $data);
		}
		$book->downloads = ($book->downloads +1);
		$book->save();
		return response()->download(base_path('public/downloads/txt/'.$book->id.'.txt'), $book->name.'.txt');
	}
}
